//
//  NSString+Extension.m
//  DGGCommonSDK
//
//  Created by dgg_hzk on 2019/11/20.
//

#import "NSString+Extension.h"
#import <CommonCrypto/CommonCrypto.h>
#import "pinyin.h"

#define EmojiCodeToSymbol(c) ((((0x808080F0 | (c & 0x3F000) >> 4) | (c & 0xFC0) << 10) | (c & 0x1C0000) << 18) | (c & 0x3F) << 24)

@implementation NSString (Extension)

+ (NSString *)emojiWithStringCode:(NSString *)stringCode{
    char *charCode = (char *)stringCode.UTF8String;
    long intCode = strtol(charCode, NULL, 16);
    return [self emojiWithIntCode:(int)intCode];
}

+ (NSString *)emojiWithIntCode:(int)intCode {
    int symbol = EmojiCodeToSymbol(intCode);
    NSString *string = [[NSString alloc] initWithBytes:&symbol length:sizeof(symbol) encoding:NSUTF8StringEncoding];
    if (string == nil) { // 新版Emoji
        string = [NSString stringWithFormat:@"%C", (unichar)intCode];
    }
    return string;
}

+ (NSString *)currentTime{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYYMMddHHMMss"];
    NSString *currentDate = [dateFormatter stringFromDate:[NSDate date]];
    return currentDate;
}

+ (NSString *)transformToJsonWithDic:(NSDictionary *)dic{
    NSData *data=[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return jsonStr;
}

+ (NSString *)imageToBase64:(UIImage *)originImage{
    NSData *data = UIImageJPEGRepresentation(originImage, 1.0f);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return encodedImageStr;
}

+ (NSString *)stringWithReplaceString:(NSString *)replaceString{
    return [NSString stringWithReplaceString:replaceString showString:@"暂无"];
}

//判断是否为空
+(BOOL) isEmpty:(NSString *)str{
    str = kFormat(str);
    if (str == nil || str == NULL) {
        return YES;
    }
    if ([str isKindOfClass:[NSNull class]]||[str isEqualToString:@""]||[str isEqualToString:@"(null)"]||[str isEqualToString:@"<null>"]||[str isEqualToString:@"null"]||str.length == 0) {
        return YES;
    }
    return NO;
}

+(NSString *)isEmpty:(NSString *)str replaceStr:(NSString *)replaceStr{
    if ([NSString isEmpty:str]) {
        return replaceStr;
    }else
    {
        return str;
    }
}

+ (NSString *)stringWithReplaceString:(NSString *)replaceString showString:(NSString *)showString{
    if ([NSString isEmpty:replaceString]) {
        if ([NSString isEmpty:showString]) {
            return @"";
        } else {
            return showString;
        }
    } else {
        return replaceString;
    }
}

//正则替换html标签
+ (NSString *)getZZwithString:(NSString *)string{
    //    NSRegularExpression *regularExpretion = [NSRegularExpression regularExpressionWithPattern:@"<[^>]*>|\n|&nbsp;|\r|&mdash|&ldquo|&rdquo"
    //                                                                                      options:0
    //                                                                                        error:nil];
    string = [string stringByReplacingOccurrencesOfString:@"</p>" withString:@"\n"];//段落改为换行
    string = [string stringByReplacingOccurrencesOfString:@"<br />" withString:@"\n"];//换行替换
    
    //定义HTML标签的正则表达式 @"<[p|span|div|input|img|h][^>]+>"
    //@"<[/\\w_\"=\\s]+>"
    NSRegularExpression *regularExpretion = [NSRegularExpression regularExpressionWithPattern:@"<[^>]*>"
                                                                                      options:0
                                                                                        error:nil];
    
    string = [regularExpretion stringByReplacingMatchesInString:string options:NSMatchingReportProgress range:NSMakeRange(0, string.length) withTemplate:@""];
    //html实体转换
    string = [string stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    string = [string stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"];
    string = [string stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    string = [string stringByReplacingOccurrencesOfString:@"&apos;" withString:@"'"];
    string = [string stringByReplacingOccurrencesOfString:@"&yen;" withString:@"¥"];
    string = [string stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
    
    //    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""]; //去掉空格
    //
    //    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除字符串中所有得空格及控制字符
    
    return string;
}

- (NSString *)getMMSSFromSS{
    NSInteger seconds = [self integerValue];
    //format of hour
    NSString *str_hour = [NSString stringWithFormat:@"%02ld",(long)seconds/3600];
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",(long)(seconds%3600)/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%02ld",(long)seconds%60];
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
    //    if ([str_hour integerValue] > 0) {
    //        format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
    //    } else {
    //        format_time = [NSString stringWithFormat:@"%@:%@",str_minute,str_second];
    //    }
    return format_time;
}

- (NSString *)seconds2Minutes{
    NSInteger seconds = [self integerValue];
    return [NSString stringWithFormat:@"%ld分钟",(long)ceill(seconds/60.0)];
}

- (NSString *)emoji{
    return [NSString emojiWithStringCode:self];
}

- (NSString *)firstStringSeparatedByString:(NSString *)separeted{
    NSArray *list = [self componentsSeparatedByString:separeted];
    return [list firstObject];
}

- (CGSize)sizeWithMaxWidth:(CGFloat)width andFont:(UIFont *)font{
    return [self sizeWithMaxSize:CGSizeMake(width, MAXFLOAT) textFont:font];
}

- (NSString *)originName{
    NSArray *list = [self componentsSeparatedByString:@"_"];
    NSMutableString *orgName = [NSMutableString string];
    NSUInteger count = list.count;
    if (list.count > 1) {
        for (int i = 1; i < count; i ++) {
            [orgName appendString:list[i]];
            if (i < count-1) {
                [orgName appendString:@"_"];
            }
        }
    } else {  // 防越狱的情况下，本地改名字
        orgName = list[0];
    }
    return orgName;
}

- (CGSize)sizeWithMaxSize:(CGSize)maxSize textFont:(UIFont *)font {
    CGRect rect = [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
    return rect.size;
}

- (float)getHeightWithFontSize:(int)size width:(float)width{
    return [self sizeWithMaxSize:CGSizeMake(width, MAXFLOAT) textFont:[UIFont systemFontOfSize:size]].height;
}

- (NSString*)isEmpty{
    if ([NSString isEmpty:self]) {
        return @"";
    }else
    {
        return self;
    }
}

-(NSString *)dNumber{
    NSString *str= [NSString stringWithFormat:@"%lf",[self doubleValue]];
    return kFormat([NSDecimalNumber decimalNumberWithString:str]);
}

- (float)getWidthWithFontSize:(int)size hight:(float)hight{
    return [self sizeWithMaxSize:CGSizeMake(MAXFLOAT, hight) textFont:[UIFont systemFontOfSize:size]].width;
}

-(NSString *)trimString{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

//字符串本地化
+(NSString*)localizedForKey:(NSString *)key{
    return  NSLocalizedString(key, nil);
}

+ (NSString *) md5:(NSString *)str{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, (CC_LONG)strlen(cStr), result );
    NSString *string = [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                        result[0], result[1], result[2], result[3],
                        result[4], result[5], result[6], result[7],
                        result[8], result[9], result[10], result[11],
                        result[12], result[13], result[14], result[15]
                        ];
    return  [string lowercaseString];
}

//根据文件获取MD5值
+ (NSString *)fileMD5:(NSString *)filePath{
    NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:filePath];
    if(!handle)
    {
        return nil;
    }
    CC_MD5_CTX md5;
    CC_MD5_Init(&md5);
    BOOL done = NO;
    while (!done)
    {
        NSData *fileData = [handle readDataOfLength:256];
        CC_MD5_Update(&md5, [fileData bytes], (CC_LONG)[fileData length]);
        if([fileData length] == 0)
        done = YES;
    }
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5_Final(digest, &md5);
    NSString *result = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                        digest[0], digest[1],
                        digest[2], digest[3],
                        digest[4], digest[5],
                        digest[6], digest[7],
                        digest[8], digest[9],
                        digest[10], digest[11],
                        digest[12], digest[13],
                        digest[14], digest[15]];
    return result;
}

-(NSAttributedString*)attributedStrFont:(UIFont *)font loc:(NSInteger)loc len:(NSInteger)len{
    NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:self] ;
    
    [attriString addAttribute:NSFontAttributeName value:font range:NSMakeRange(loc, len)];
    return attriString;
}

-(NSAttributedString*)attributedStrFont:(UIFont *)font loc:(NSInteger)loc len:(NSInteger)len color:(UIColor *)color{
    NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:self] ;
    
    [attriString addAttribute:NSFontAttributeName value:font range:NSMakeRange(loc, len)];
    [attriString addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(loc, len)];
    return attriString;
}

-(NSAttributedString*)attrStringloc:(NSInteger)loc len:(NSInteger)len color:(UIColor *)color backgroundColor:(UIColor*)backgroundColor{
    NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:self] ;
    [attriString addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(loc, len)];
    if (backgroundColor != nil) {
        [attriString addAttribute:NSBackgroundColorAttributeName value:backgroundColor range:NSMakeRange(loc, len)];
    }
    return attriString;
}

- (NSString *)separatedDigitString{
    if ([NSString isEmpty:self]) {
        return @"0.00";
    }
    NSDecimalNumber *str = [[NSDecimalNumber alloc] initWithString:self];
    NSString *ssss = [NSString stringWithFormat:@"%0.2lf", str.doubleValue];
    NSRange iStart = [ssss rangeOfString:@"."];
    NSString * temp = [ssss substringToIndex:iStart.location];
    NSString * decimalPointSeparated =[ssss substringFromIndex:iStart.location];
    temp = [self integerAddCommaWithString:temp];
    temp = [temp stringByAppendingString:decimalPointSeparated];
    return temp;
}

//判断开头符号
-(NSString *)judgeSymbol:(NSString *)string{
    NSMutableString * mutableString =[NSMutableString stringWithString:string];
    //没有负号 逗号开头
    if ([mutableString hasPrefix:@","]) {
        string= [mutableString substringFromIndex:1];
        return   string;
    }else if ([mutableString hasPrefix:@"-,"]){ //负号开头
        NSString * s = @"-";
        string= [mutableString substringFromIndex:2];
        return   [s stringByAppendingString:string];
    }else if([mutableString hasPrefix:@"+,"]){
        NSString * s = @"+";
        string= [mutableString substringFromIndex:2];
        return   [s stringByAppendingString:string];
    }
    return(NSString *) mutableString;
    
    
}

//添加逗号
-(NSString *)integerAddCommaWithString:(NSString *)string{
    NSInteger count = string.length;
    
    NSMutableString * mutableString =[NSMutableString stringWithString:string];
    if (count>3) {
        NSInteger k = count/3;
        for (int i = 0; i<k; i++) {
            [mutableString insertString:@"," atIndex:count-3*(i+1)];
        }
    }else{
        return string;
    }
    NSString * temp = (NSString *)mutableString;
    return  [self judgeSymbol:temp];
}

- (NSString*)getPinYin{
    return  [[NSString stringWithFormat:@"%c",pinyinFirstLetter([self characterAtIndex:0])] uppercaseString];
}

- (NSString *)getAllPinyin{
    NSString *pinyin = [self transformToPinyin];
    return [pinyin stringByReplacingOccurrencesOfString:@" " withString:@""];
}

- (NSString *)getAllPinyinFirstLetter{
    NSString *pinyin = [self transformToPinyin];
    NSString *pinyinFirstLetter = @"";
    for (NSString *word in [pinyin componentsSeparatedByString:@" "]) {
        if (word.length > 0) {
            pinyinFirstLetter = [pinyinFirstLetter stringByAppendingString:[word substringToIndex:1]];
        }
    }
    return pinyinFirstLetter;
}

- (void)getAllPinyin:(void(^)(NSString *allPinyin))allPinyin allPinyinFirstLetter:(void(^)(NSString *allPinyinFirstLetter))allPinyinFirstLetter{
    NSString *pinyin = [self transformToPinyin];
    if (allPinyin) {
        allPinyin([pinyin stringByReplacingOccurrencesOfString:@" " withString:@""]);
    }
    if (allPinyinFirstLetter) {
        NSString *pinyinFirstLetter = @"";
        for (NSString *word in [pinyin componentsSeparatedByString:@" "]) {
            if (word.length > 0) {
                pinyinFirstLetter = [pinyinFirstLetter stringByAppendingString:[word substringToIndex:1]];
            }
        }
        allPinyinFirstLetter(pinyinFirstLetter);
    }
}

- (NSString *)transformToPinyin{
    NSMutableString *mutableString = [NSMutableString stringWithString:self];
    CFStringTransform((CFMutableStringRef)mutableString, NULL, kCFStringTransformToLatin, false);
    mutableString = (NSMutableString *)[mutableString stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
    return [mutableString stringByReplacingOccurrencesOfString:@"'" withString:@""];
}

+ (NSString *)documentPath{
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    return documentPath;
}

- (NSString *)changeAsset{
    if (![NSString isEmpty:self]) {
        NSInteger num = [self integerValue];
        if (num<10000) {
            return self;
        } else {
            NSString *str = [NSString stringWithFormat:@"%f",num/10000.0];
            NSRange range = [str rangeOfString:@"."];
            str = [str substringToIndex:range.location+2];
            if ([str hasSuffix:@".0"]) {
                return [NSString stringWithFormat:@"%@万",[str substringToIndex:str.length-2]];
            }
            return [NSString stringWithFormat:@"%@万",str];
        }
    }
    return @"0";
}

- (NSString *)localNumberString{
    NSString *valueString = [NSString isEmpty:self replaceStr:@"0"];
    NSNumber *numberValue = [NSNumber numberWithDouble:valueString.doubleValue];
    return [NSNumberFormatter localizedStringFromNumber:numberValue numberStyle:NSNumberFormatterDecimalStyle];
}

- (NSString *)monetization{
    if ([NSString isEmpty:self]) {
        return @"0.00";
    }
    NSNumberFormatter *formatter = [NSNumberFormatter new];
    formatter.numberStyle = kCFNumberFormatterDecimalStyle;
    formatter.maximumFractionDigits = 2;
    formatter.minimumFractionDigits = 2;
    NSNumberFormatter *noStyleFormatter = [NSNumberFormatter new];
    [noStyleFormatter setNumberStyle:NSNumberFormatterNoStyle];
    NSString *currencyStr = [formatter stringFromNumber:[noStyleFormatter numberFromString:self]];
    return currencyStr;
}

- (NSString *)base64String{
    if([NSString isEmpty:self]){
        return @"";
    }
    NSData *baseData = [self dataUsingEncoding:NSUTF8StringEncoding];
    return [baseData base64EncodedStringWithOptions:(NSDataBase64Encoding64CharacterLineLength)];
}

- (NSString *)decodeBaseString{
    if([NSString isEmpty:self]){
        return @"";
    }
    NSData *baseData = [[NSData alloc] initWithBase64EncodedString:self options:(NSDataBase64DecodingIgnoreUnknownCharacters)];
    if(baseData){
        return [[NSString alloc] initWithData:baseData encoding:NSUTF8StringEncoding];
    }
    return @"";
}

- (NSString *)appendOSSImageWidth:(NSInteger)tWidth tHeight:(NSInteger)tHeight{
    NSString *result = kFormat(self);
    result = [result stringByAppendingFormat:@"?x-oss-process=image/resize,w_%ld,h_%ld", tWidth, tHeight];
    return result;
}

- (NSString *)appendOSSImage:(NSString *)ossPath tWidth:(NSInteger)tWidth tHeight:(NSInteger)tHeight{
    NSString *result = kFormat(self);
    result = [result stringByAppendingFormat:@"?%@,w_%ld,h_%ld",ossPath, tWidth, tHeight];
    return result;
}

@end
